package com.springboot.manager.aop;

import com.springboot.manager.common.CommonResult;
import com.springboot.manager.util.LogServiceUtil;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

/**
 * @version v1.0
 * @ProjectName: hlk-microservice-ails
 * @ClassName: ExceptionAop
 * @Description: 异常aop 拦截请求信息
 * @Author: zhangzl
 * @Date: 2021-08-12 8:51
 */
public class ExceptionAop implements MethodInterceptor {

    @Value("${log.aop.exception.enable}")
    private String exceptionEnable;

    @Autowired
    private LogServiceUtil logServiceUtil;

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object result = null;
        String exceptionMsg = "";

        //是否开启异常拦截
        if ("true".equals(exceptionEnable)) {
            try {
                result = invocation.proceed();
            } catch (Exception e) {
                //存储异常日志
                logServiceUtil.saveExceptionLog(e);
                exceptionMsg = e.getMessage();
            }
        } else {
            result = invocation.proceed();
        }
        stopWatch.stop();
        //存储操作日志
        logServiceUtil.saveOperateLog(invocation, stopWatch, result);
        if (!StringUtils.isEmpty(exceptionMsg)) {
            return new CommonResult<Object>(0,exceptionMsg);
        }
        return result;
    }
}